﻿using Sustainalytics.ESG.Entities;
using Sustainalytics.Synchronization.Validation.ValidationRules.Common;
using System;
using System.Linq;

namespace Sustainalytics.Synchronization.Validation.ValidationRules.Core
{
    public class IndicatorRawScoreChangeRule : CoreRule<RPCompanyESGComputationResult>
    {
        private const float Tolerance = (float)1e-10;

        public override Severity Severity => Severity.Yellow;
        public override BusinessResearchProduct BusinessResearchProduct => BusinessResearchProduct.Core;
        public override string Code => "YR10";
        public override string InformationalMessage => "Significant indicator (including event indicators) raw score changes (100 to 0 or 0 to 100)";

        public IndicatorRawScoreChangeRule()
        {
            For(x => x.Indicators).When(Validator).WithKey(x => x.Id).WithMessage("The company {0} #{1}# does not have compliant indicators score change");
        }

        private bool Validator(RPCompanyESGComputationResult validatedResult, RPCompanyESGComputationResult referenceResult)
        {
            var triggerIndicators = validatedResult.Indicators.Where(v => referenceResult.Indicators.Any(r => (r.Code == v.Code)
                    && ((Math.Abs(r.RawScore) < Tolerance && Math.Abs(v.RawScore - 100) < Tolerance)
                    || (Math.Abs(r.RawScore - 100) < Tolerance && Math.Abs(v.RawScore) < Tolerance))))
                    .Select(x => x.Code);

            if (!triggerIndicators.Any())
                return true;

            SetTriggersMessages(triggerIndicators);

            return false;
        }
    }
}
